package ru.vsu.cs.kis.elections.socketexchenge;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

import java.util.concurrent.Future;

import ru.vsu.cs.kis.elections.Statistic;
import ru.vsu.cs.kis.elections.dto.CandidateDto;
import ru.vsu.cs.kis.elections.dto.PrecinctDto;
import ru.vsu.cs.kis.elections.socketexchenge.commands.Command;
import ru.vsu.cs.kis.elections.socketexchenge.commands.PingCommand;

public class CommandController {

	private Socket aSocket = null;
	private ExecutorService service = null;
	private InetAddress serverAddress = null;
	private OutputStream output=null;
	private InputStream input=null;
	private Integer port = 4444;

	public CommandController(InetAddress serverAddress, Integer port) {
		service = Executors.newCachedThreadPool();
		this.port = port;
		this.serverAddress = serverAddress;
	}

	private Command runAsyn(Command aCommand) {
		Future<Command> f = null;
		Command c = null;
		f = service.submit(new AsynTask(aCommand));
		try {
			c = f.get();			
			return c;
		} catch (InterruptedException e) {
			e.printStackTrace();
		} catch (ExecutionException e) {
			e.printStackTrace();
		} 
		return null;
	}

	public Boolean authentication(String address, String password) {
		return false;
	}

	public Integer ping() {
		Command c;
		try {
			aSocket = new Socket(serverAddress, port);
			Statistic.openClienSocketCount++;
			this.output=aSocket.getOutputStream();
			this.input=aSocket.getInputStream();
			c = runAsyn(new PingCommand(output,input));
			Integer ping = ((PingCommand) c).getPing();
			output.close();
			input.close();
			aSocket.close();
			Statistic.closeClienSocketCount++;
			System.out.printf("client sockets  open: %d  close: %d \n",Statistic.openClienSocketCount,Statistic.closeClienSocketCount);
			return ping;
		} catch (IOException e) {
			e.printStackTrace();
		}
		return (-1);
	}

	public Integer sendVotes(PrecinctDto precinctDtoForSend) {
		return -1;
	}

	public CandidateDto getCandidates() {
		return null;
	}

	public CandidateDto getResult() {
		return null;
	}

	public CandidateDto getAllResult() {
		return null;
	}

}
